<template>
  <div>
    <div style="display: flex">
      <div style="padding: 0 7px">
        <el-tree
          style="width: 200px; max-width: 600px"
          :data="state.tree"
          :props="defaultProps"
          :default-expanded-keys="[2, 3]"
          @node-click="handleNodeClick"
        />
      </div>
      <div style="flex: 1">
        <div style="display: flex; margin-bottom: 7px">
          <el-input
            v-model="state.search"
            style="width: 199px; margin-right: 20px"
            placeholder="请输入用户名称"
            clearable
          />
          <el-button type="primary" :icon="Search" @click="onSearch">
            搜索
          </el-button>
        </div>
        <div>
          <el-table :data="state.userList" border style="width: 100%">
            <el-table-column type="index" label="序列号" width="70" />
            <el-table-column prop="id" label="id" />
            <el-table-column prop="nickname" label="Name" width="90" />
            <el-table-column prop="email" label="邮箱" width="200" />
            <el-table-column prop="roleId" label="角色" width="100" />
            <el-table-column fixed="right" label="操作">
              <template #default="scope">
                <el-button
                  :icon="Delete"
                  link
                  type="danger"
                  size="small"
                  @click="handleDeleteClick(scope.row.id)"
                  >删除</el-button
                >
                <el-button
                  :icon="Edit"
                  link
                  type="primary"
                  size="small"
                  @click="handlerole(scope.row.id)"
                  >分配角色</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
    </div>
    <!--  -->
    <el-dialog
      v-model="state.dialogVisible"
      title="分配角色"
      width="500"
      draggable
    >
      <div class="m-4">
        <el-select
          v-model="state.roleForm.roleType"
          value-key="id"
          placeholder="Select"
          style="width: 240px"
        >
          <el-option
            v-for="item in options"
            :key="item"
            :label="item.label"
            :value="item.roleType"
          />
        </el-select>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="state.dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="editRole"> 确认 </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
<script lang="ts" setup>
import {
  getCompanyGroup,
  getGroupUser,
  deleteUser,
  editUserRole
} from "@/api/user";
import { myCompany } from "@/api/company";
import { onMounted, reactive, ref } from "vue";
import { Delete, Edit, Search } from "@element-plus/icons-vue";
import { ElMessage, ElMessageBox } from "element-plus";
const state = reactive({
  companyDetails: {},
  userList: [],
  userInfo: [],
  search: "",
  tree: [],
  dialogVisible: false,
  roleForm: {
    companyUserId: "",
    roleType: ""
  }
});
const defaultProps = {
  children: "children",
  label: "name"
};
const onSearch = function () {};

let roleMap = {
  0: "超级管理员",
  1: "管理员",
  2: "普通成员"
};
//点击获取每个组的人员
const handleNodeClick = data => {
  getGroupUser(data.id).then(res => {
    state.userList = [];
    if (res.code == 200) {
      res.data.forEach(i => {
        if (i.type == "USER") {
          i.roleId = roleMap[i.roleId];
          state.userList.push(i);
        } else {
          // let tree = {}
          //  console.log(i.type)
          //  state.tree.children.forEach((element,index) => {
          //    if (element.id == data.id) {
          //      tree.id = i.id
          //     tree.name=i.name
          //     state.tree.children[index].push(tree)
          //   }
          //  });
        }
      });
    }
  });
};
// 点击按钮删除人员
const handleDeleteClick = (id: BigInt) => {
  console.log(id);
  ElMessageBox.confirm("是否删除用户", "删除用户", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning"
  })
    .then(() => {
      deleteUser(id).then(res => {
        if (res.code == 200) {
          ElMessage({
            type: "success",
            message: "删除成功"
          });
          initData();
        } else {
          ElMessage({
            type: "warning",
            message: "删除失败"
          });
        }
      });
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "Delete canceled"
      });
    });
};
//分配角色
const handlerole = id => {
  state.roleForm.companyUserId = id;
  state.dialogVisible = true;
};
const options = ref([
  { roleType: "SYS_ADMIN", label: "超级管理员" },
  { roleType: "ADMIN", label: "管理员" },
  { roleType: "USER", label: "普通成员" }
]);
//分配角色
const editRole = async () => {
  console.log(state.roleForm);
  const result = await editUserRole(state.roleForm);
  if (result.code == 200) {
    ElMessage({
      type: "success",
      message: "分配角色成功"
    });
    initData();
    console.log(state.userList);
  } else {
    ElMessage({
      type: "warning",
      message: "分配角色失败"
    });
  }
  state.dialogVisible = false;
};

const initData = async () => {
  //获得公司的信息
  const result = await myCompany();
  if (result.code == 200) {
    state.companyDetails = result.data;
    console.log(state.companyDetails);
  }
  const res1 = await getCompanyGroup();
  if (res1.code == 200) {
    res1.data.forEach(async (item, index) => {
      const res = await getGroupUser(item.id);
      console.log(res);
      if (res.code == 200) {
        let tree2 = {};
        tree2.id = item.id;
        tree2.name = item.name;
        tree2.children = res.data;
        res1.data = [];
        res1.data.push(tree2);
      }
    });

    let tree = {};
    // tree.companyId=state.companyDetails.id;
    tree.id = 0;
    tree.name = state.companyDetails.name;
    tree.children = res1.data;
    // await sleep(1000)
    state.tree.push(tree);
    // console.log(666)
    console.log(state.tree);
  }
  //初始化获得人员
  getGroupUser(0).then(res => {
    state.userList = [];
    if (res.code == 200) {
      res.data.filter(i => {
        if (i.type == "USER") {
          i.roleId = roleMap[i.roleId];
          state.userList.push(i);
        }
      });
    }
  });
};
onMounted(() => {
  initData();
});
</script>
